package xin.clips.web.controller.gy.analy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import xin.clips.common.annotation.VisistLog;
import xin.clips.common.core.controller.BaseController;
import xin.clips.common.core.domain.entity.SysDictData;
import xin.clips.common.core.domain.entity.SysUser;
import xin.clips.common.utils.ShiroUtils;
import xin.clips.common.utils.StringUtils;
import xin.clips.system.domain.SysLogininfor;
import xin.clips.system.domain.SysOperLog;
import xin.clips.system.domain.SysVisitLog;
import xin.clips.system.domain.gy.GyDevice;
import xin.clips.system.dto.GyDeviceStatusDataDTO;
import xin.clips.system.dto.NameValueDataDTO;
import xin.clips.system.service.*;
import xin.clips.system.service.gy.IGyDeviceService;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备状态分析
 *
 * @author clips
 * @date 2023-03-15
 */
@Controller
@RequestMapping("/gy/userAnaly")
public class UserAnalyController extends BaseController {

    private String prefix = "gy/userAnaly";

    @Autowired
    private IGyDeviceService deviceService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ISysLogininforService logininforService;

    @Autowired
    private ISysOperLogService operLogService;

    @Autowired
    private ISysVisitLogService visitLogService;



    @RequiresPermissions("gy:userAnaly:count")
    @VisistLog(title = "用户行为分析统计")
    @GetMapping()
    public String userAnaly(ModelMap mmap) {
        Long userId = ShiroUtils.getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        String locationId = sysUser.getLocationId();
        SysDictData typeDictData = new SysDictData();
        typeDictData.setDictType("gy_device_type");
        List<SysDictData> typeDicts = dictDataService.selectDictDataList(typeDictData);
        SysDictData statusDictData = new SysDictData();
        statusDictData.setDictType("gy_device_status");
        List<SysDictData> statusDicts = dictDataService.selectDictDataList(statusDictData);
        List<String> typeList = new ArrayList<>();
        for (SysDictData typeData : typeDicts) {
            typeList.add(typeData.getDictLabel());
        }
        List<String> statusList = new ArrayList<>();
        List<GyDeviceStatusDataDTO> gyDeviceStatusDatumDTOS = new ArrayList<>();
        for (SysDictData statusData : statusDicts) {
            statusList.add(statusData.getDictLabel());
            GyDeviceStatusDataDTO gyDeviceStatusDataDTO = new GyDeviceStatusDataDTO();
            gyDeviceStatusDataDTO.setName(statusData.getDictLabel());
            gyDeviceStatusDatumDTOS.add(gyDeviceStatusDataDTO);
        }
        List<ArrayList> list = new ArrayList();

        for (SysDictData statusData : statusDicts) {
            ArrayList temp = new ArrayList();
            for (SysDictData type : typeDicts) {
                GyDevice device = new GyDevice();
                if (StringUtils.isNotEmpty(locationId)) {
                    device.setLocationId(Integer.parseInt(locationId));
                }
                device.setDeviceType(Integer.parseInt(type.getDictValue()));
                device.setDeviceStatus(Integer.parseInt(statusData.getDictValue()));
                Integer total = deviceService.selectGyDeviceByDeviceTypeAndStatus(device);
                temp.add(total.toString());
            }
            list.add(temp);
        }

        mmap.put("typeArray", typeList.toArray());
        mmap.put("gyDeviceStatusAnalys", gyDeviceStatusDatumDTOS);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
            //构建json数组
            JSONObject stObject = new JSONObject();
            stObject.put("name", statusList.get(i));
            stObject.put("type", "bar");
            stObject.put("stack", "one");
            stObject.put("data", list.get(i).stream().toArray());
            jsonArray.add(stObject);
        }
        mmap.put("jsonArray", jsonArray);

        /*统计最新一周登录量、访问量*/
        SysVisitLog visistLog = new SysVisitLog();
        List<SysVisitLog> sceneData = visitLogService.selectVisitTop3(visistLog);
        List<String> keyData = new ArrayList();
        List<String> valueData = new ArrayList();
        for (SysVisitLog temp : sceneData) {
            keyData.add(temp.getModuleName());
            valueData.add(temp.getCount());
        }

        mmap.put("keyData", keyData.toArray());
        mmap.put("valueData", valueData.toArray());

        //登录用户
        Map<String, String> loginDayMap = new HashMap<>(); //登录量 每日统计数据，key是日期，value是值，默认值是0.
        Map<String, String> visitDayMap = new HashMap<>(); //访问量 每日统计数据，key是日期，value是值，默认值是0.
        List<String> dateList = new ArrayList<>();
        String startTime = loginDayMap.get(6);
        String endTime = loginDayMap.get(0);
        for (int i = 7; i >= 0; i--) {
            String date = LocalDate.now().minusDays(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            if (i == 7) {
                startTime = date;
            }
            if (i == 0) {
                endTime = date;
            }
            dateList.add(date);
            loginDayMap.put(date, "0");
            visitDayMap.put(date, "0");
        }
        SysLogininfor logininfor = new SysLogininfor();
        logininfor.getParams().put("beginTime", startTime + " 00:00:00");
        logininfor.getParams().put("endTime", endTime + " 23:59:59");

        List<SysLogininfor> logininfors = logininforService.selectLoginDayAnalyByTime(logininfor);
        for (SysLogininfor loginInfo : logininfors) {
            loginDayMap.put(loginInfo.getDat(), loginInfo.getCount()); //将取到的数据覆盖初始的
        }
        ArrayList<String> dayLoginCountArray = new ArrayList<>();
        for (String date : dateList) {
            dayLoginCountArray.add(loginDayMap.get(date)); //将值转换为string集合。
        }

        //日期访问量统计
        SysVisitLog sysVisitLog = new SysVisitLog();
        sysVisitLog.getParams().put("beginTime", startTime + " 00:00:00");
        sysVisitLog.getParams().put("endTime", endTime + " 23:59:59");

        List<SysVisitLog> sysVisitLogs = visitLogService.selectVisitDayAnalyByTime(sysVisitLog);

        for (SysVisitLog visitLog : sysVisitLogs) {
            visitDayMap.put(visitLog.getDat(), visitLog.getCount()); //将取到的数据覆盖初始的
        }

        ArrayList<String> dayVisitCountArray = new ArrayList<>();
        for (String date : dateList) {
            dayVisitCountArray.add(visitDayMap.get(date)); //将值转换为string集合。
        }

        mmap.put("dayLoginCountArray", dayLoginCountArray.toArray());  //登录量[]
        mmap.put("rqArray", dateList.toArray());//日期array
        mmap.put("dayVisitCountArray", dayVisitCountArray.toArray()); //访问量[]

        //按时间段统计
        List<SysOperLog> timeOperLogs = operLogService.selectOperLogByTime(new SysOperLog());

        List<NameValueDataDTO> timeOperLogsData = new ArrayList();

        timeOperLogsData.add( new NameValueDataDTO("00:00-08:00",timeOperLogs.get(0).getCount().toString()));
        timeOperLogsData.add(   new NameValueDataDTO("08:00-16:00",timeOperLogs.get(1).getCount().toString()));
        timeOperLogsData.add( new NameValueDataDTO("16:00-24:00",timeOperLogs.get(2).getCount().toString()));

        mmap.put("timeOperLogsData", timeOperLogsData.toArray());
        //

        //按时间段统计
        /* 分用户登录量饼图 */
        List<SysOperLog> operLogs = operLogService.selectOperLogTotalByOperName(new SysOperLog());

        List<NameValueDataDTO> byUserLoginAnaly = new ArrayList<>();
        Long otherTotal = 0l;
        NameValueDataDTO nameValueDataDTO =null;
        for (int i = 0; i < 5; i++) {
            nameValueDataDTO = new NameValueDataDTO();
            nameValueDataDTO.setName(operLogs.get(i).getOperName());
            nameValueDataDTO.setValue(operLogs.get(i).getCount().toString());
            byUserLoginAnaly.add(nameValueDataDTO);
        }
        nameValueDataDTO = new NameValueDataDTO();
        nameValueDataDTO.setName("其他用户");
        for (int i = 5; i < operLogs.size(); i++) {
            otherTotal += operLogs.get(i).getCount();
        }
        nameValueDataDTO.setValue(otherTotal.toString());
        byUserLoginAnaly.add(nameValueDataDTO);
        mmap.put("byUserLoginAnaly", byUserLoginAnaly.toArray());
        /* 分用户登录量饼图 end */

        /*返回登录、用户访问量的 柱状图统计*/
        Long loginTotal = logininforService.selectTotal();
        Long loginAndVistorTotal = visitLogService.selectTotal();
        Long operlogTotal = operLogService.selectTotal();
        List<String> loginData = new ArrayList();
        List<String> loginAndVistorTotalValueData = new ArrayList();

        loginData.add("登录数");
        loginData.add("用户访问数");
        loginData.add("系统模块操作数");
        loginAndVistorTotalValueData.add(String.valueOf(loginTotal));
        loginAndVistorTotalValueData.add(String.valueOf(loginAndVistorTotal));
        loginAndVistorTotalValueData.add(String.valueOf(operlogTotal));

        mmap.put("loginTotal", loginData.toArray());
        mmap.put("loginAndVistorTotalValueData", loginAndVistorTotalValueData.toArray());
        return prefix + "/userAnaly";
    }

}
